/*
 *   项目名称：train12306
 *   文件名称：com.xiaolon.train12306.gateway.config.LoginMemberFilter
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/26
 *
 */
package com.xiaolon.train12306.gateway.config;

import com.xiaolon.train12306.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 类描述： LoginMemberFilter
 * 请求过滤器
 **/
@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {


    private static final Logger LOG = LoggerFactory.getLogger(LoginMemberFilter.class);

    /**
     * 过滤请求（包括uri、token校验）
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取uri
        String path = exchange.getRequest().getURI().getPath();

        // 排除不需要过滤的请求
        if(path.contains("/admin")
                || path.contains("/hello")
                || path.contains("/member/member/login")
                || path.contains("/member/member/send-code")
        ){
            LOG.info("不需要登录验证: {}", path);
            return chain.filter(exchange);
        }else{
            LOG.info("需要登录验证: {}", path);
        }

        // 获取header的token参数并校验

        String token = exchange.getRequest().getHeaders().getFirst("token");
        LOG.info("会员登录验证开始，token: {}", token);
        if(token == null || token.isEmpty()){
            LOG.info("token为空, 请求被过滤");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 校验token是否通过
        boolean validate = JwtUtil.validate(token);
        if(validate){
            LOG.info("token有效，放行改请求");
            return chain.filter(exchange);
        }else{
            LOG.warn("token无效，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    /**
     * 过滤器优先级设值，值越小，越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}